package org.mspring.mlog.dao.impl;

import org.mspring.mlog.dao.ArticleDao;
import org.mspring.mlog.entity.Article;
import org.mspring.mlog.entity.em.ArticleStatus;
import org.mspring.nbee.orm.dao.callback.SqlQueryCallback;
import org.mspring.nbee.orm.dao.impl.BaseDao;
import org.mspring.nbee.orm.dao.sql.Sql;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @author Gao Youbo
 * @since 2014-12-04 17:58:26
 */
@Repository
public class ArticleDaoImpl extends BaseDao<Article> implements ArticleDao {
    @Override
    public int getArticleViewCount(long articleId) {
        Sql sql = new Sql("select view_count from t_article where id = ?", articleId);
        return executeQuery(sql, new SqlQueryCallback<Integer>() {
            @Override
            public Integer execute(ResultSet rs) throws SQLException {
                if (rs.next()) {
                    return rs.getInt("view_count");
                }
                return -1;
            }
        });
    }

    @Override
    public boolean updateArticleViewCount(long articleId, int viewCount) {
        Sql sql = new Sql("update t_article set view_count = ? where id = ?", viewCount, articleId);
        return executeUpdate(sql) > 0;
    }

    @Override
    public List<Article> listLatestArticle(int limit) {
        Sql sql = new Sql("select * from t_article where status = ? order by id desc limit ?", ArticleStatus.NORMAL, limit);
        return listBySql(sql);
    }

    @Override
    public List<Article> listHotArticle(int limit) {
        Sql sql = new Sql("select * from t_article where status = ? order by view_count desc limit ?", ArticleStatus.NORMAL, limit);
        return listBySql(sql);
    }
}
